<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/4
 * Time: 9:26
 */

namespace app\api\controller\v1;


/*
 * @地址管理
 * */

use app\api\controller\BaseController;
use app\api\model\User;
use app\api\service\ToToken;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address extends BaseController
{
    protected $beforeActionList = [
        'checkPrimaryScope'=>['only'=>'createOrUpdateAddress'],
    ];


//    /*前置操作:当执行second或third方法时,提前执行first方法*/
//    protected $beforeActionList = [
//        'first' => ['only'=>'second,third'],
//    ];
//
//    protected function first(){
//        echo 'first';
//    }
//    /*API接口*/
//    public function second(){
//        echo 'second';
//    }
//    /*API接口*/
//    public function third(){
//        echo 'third';
//    }


    /*
    添加或更新地址
   */
    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        //1.根据token获取用户信息uid
        $uid = ToToken::getCurrentUid();
        //2.根据uid来查询用户数据,判断用户是否存在,不存在抛出异常
        $user = User::get($uid);
        if (!$user){
            throw new UserException();
        }
        //3.获取用户从客户端传过的地址信息
        $dataArray = $validate->getDataByRule(input('post.'));

        //4.根据用户地址信息是否存在,来判断是新增还是跟新
        $userAddress = $user->address;
        if (!$userAddress){
              $user->address()->save($dataArray);
        }else{
            $user->address->save($dataArray);
        }
//        return $user;
        return json(new SuccessMessage(),201);
    }

}